package com.birdboot.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpServletResponse {
    private Socket socket;
    private int codeStatus = 200;
    private String statusReason = "OK";
    private File ContentFile;
    private Map<String,String> headers = new HashMap<>();

    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }

    public int getCodeStatus() {
        return codeStatus;
    }

    public void setCodeStatus(int codeStatus) {
        this.codeStatus = codeStatus;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return ContentFile;
    }

    public void setContentFile(File contentFile) {
        ContentFile = contentFile;
    }

    public void Response() throws IOException {
        Println("HTTP/1.1 "+codeStatus+" "+statusReason);
        Println("Content-Type: text/html");
        Println("Content-Length: "+ ContentFile.length());
        Println("");
        FileInputStream fis = new FileInputStream(ContentFile);
        OutputStream out = socket.getOutputStream();
        byte[] buf = new byte[1024*10];
        int d=0;
        while ((d=fis.read(buf))!=-1)
        {
            out.write(buf,0,d);
        }
    }

    void Println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] bytes = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(bytes);
        out.write(13);
        out.write(10);
    }

    public void addHeader(String key,String value) {
        headers.put(key,value);
    }
}
